package com.naiyumie.ncalculator;

import java.util.Scanner;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.Selection;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.naiyumie.llscal.Calculator;

public class FourFundamentalRules01Activity extends KingWangJjangActivity {

	EditText et1 = null, et2 = null;
	String msg = null;
	// 방향 
	Button btnRight = null, btnLeft = null, btnFirst = null, btnLast = null;
	// 숫자
	Button btn0 = null, btn1 = null, btn2 = null, btn3 = null, btn4 = null, btn5 = null, btn6 = null, btn7 = null, btn8 = null, btn9 = null;
	// 사칙연산
	Button btnPlus = null, btnMinus = null, btnAsterisk = null, btnDivide = null;
	// ( ) .
	Button btnLeftParenthesis = null, btnRightParenthesis = null, btnPeriod = null; 
	// =
	Button btnEqualSign = null;
	// bs, clear
	Button btnBackSpace = null, btnClear = null;

	Calculator c = new Calculator();
	Scanner sc = new Scanner(System.in);
	String infixExpression, postfixExpression;
	double result = 0.0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_four_fundamental_rules_01);
		Intent fromIntent = getIntent();
		msg = fromIntent.getStringExtra("MSG");
		this.setMsg(msg);
		this.callMethod();
		tvTitle.setText(R.string.category01);
		callKeyPad();

		
		// EditText
		et1 = (EditText) findViewById(R.id.et1);
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(et1.getWindowToken(), 0);
		et1.setOnClickListener(keyPadAction);
		et1.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
				imm.hideSoftInputFromWindow(et1.getApplicationWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
				return true;
			}
		});

		et2 = (EditText) findViewById(R.id.et2);
		et2.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
				imm.hideSoftInputFromWindow(et2.getApplicationWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
				return true;
			}
		});
		imm.hideSoftInputFromWindow(et2.getWindowToken(), 0);
	}
	
	// 키패드의 호출
	public void callKeyPad() {
		// 방향
		btnRight = (Button) findViewById(R.id.btnRight);
		btnRight.setOnClickListener(keyPadAction);
		btnLast = (Button) findViewById(R.id.btnLast);
		btnLast.setOnClickListener(keyPadAction);
		btnLeft = (Button) findViewById(R.id.btnLeft);
		btnLeft.setOnClickListener(keyPadAction);
		btnFirst = (Button) findViewById(R.id.btnFirst);
		btnFirst.setOnClickListener(keyPadAction);
		// 숫자
		btn0 = (Button) findViewById(R.id.btn0);
		btn0.setOnClickListener(keyPadAction);
		btn1 = (Button) findViewById(R.id.btn1);
		btn1.setOnClickListener(keyPadAction);
		btn2 = (Button) findViewById(R.id.btn2);
		btn2.setOnClickListener(keyPadAction);
		btn3 = (Button) findViewById(R.id.btn3);
		btn3.setOnClickListener(keyPadAction);
		btn4 = (Button) findViewById(R.id.btn4);
		btn4.setOnClickListener(keyPadAction);
		btn5 = (Button) findViewById(R.id.btn5);
		btn5.setOnClickListener(keyPadAction);
		btn6 = (Button) findViewById(R.id.btn6);
		btn6.setOnClickListener(keyPadAction);
		btn7 = (Button) findViewById(R.id.btn7);
		btn7.setOnClickListener(keyPadAction);
		btn8 = (Button) findViewById(R.id.btn8);
		btn8.setOnClickListener(keyPadAction);
		btn9 = (Button) findViewById(R.id.btn9);
		btn9.setOnClickListener(keyPadAction);
		// 사칙연산
		btnPlus = (Button) findViewById(R.id.btnPlus);
		btnPlus.setOnClickListener(keyPadAction);
		btnMinus = (Button) findViewById(R.id.btnMinus);
		btnMinus.setOnClickListener(keyPadAction);
		btnAsterisk = (Button) findViewById(R.id.btnAsterisk);
		btnAsterisk.setOnClickListener(keyPadAction);
		btnDivide = (Button) findViewById(R.id.btnDivide);
		btnDivide.setOnClickListener(keyPadAction);
		// ( ) .
		btnLeftParenthesis = (Button) findViewById(R.id.btnLeftParenthesis);
		btnLeftParenthesis.setOnClickListener(keyPadAction);
		btnRightParenthesis = (Button) findViewById(R.id.btnRightParenthesis);
		btnRightParenthesis.setOnClickListener(keyPadAction);
		btnPeriod = (Button) findViewById(R.id.btnPeriod);
		btnPeriod.setOnClickListener(keyPadAction);
		// =
		btnEqualSign = (Button) findViewById(R.id.btnEqualSign);
		btnEqualSign.setOnClickListener(keyPadAction);
		// bs, clear
		btnBackSpace = (Button) findViewById(R.id.btnBackSpace);
		btnBackSpace.setOnClickListener(keyPadAction);
		btnClear = (Button) findViewById(R.id.btnClear);
		btnClear.setOnClickListener(keyPadAction);

	}

	// 키패드 리스너
	View.OnClickListener keyPadAction = new OnClickListener() {

		@Override
		public void onClick(View v) {

			String keyText;
			switch (v.getId()) {
			// EditText
			case R.id.et1:
			case R.id.et2:
				disEnableInput();

				break;
			// 방향
			case R.id.btnFirst:
				setCursor("first");
				break;
			case R.id.btnLeft:
				setCursor("left");
				break;
			case R.id.btnRight:
				setCursor("right");
				break;
			case R.id.btnLast:
				setCursor("last");
				break;
			// 숫자
			case R.id.btn0:
				keyText = "0";
				setTextEnabled(keyText);
				break;
			case R.id.btn1:
				keyText = "1";
				setTextEnabled(keyText);
				break;
			case R.id.btn2:
				keyText = "2";
				setTextEnabled(keyText);
				break;
			case R.id.btn3:
				keyText = "3";
				setTextEnabled(keyText);
				break;
			case R.id.btn4:
				keyText = "4";
				setTextEnabled(keyText);
				break;
			case R.id.btn5:
				keyText = "5";
				setTextEnabled(keyText);
				break;
			case R.id.btn6:
				keyText = "6";
				setTextEnabled(keyText);
				break;
			case R.id.btn7:
				keyText = "7";
				setTextEnabled(keyText);
				break;
			case R.id.btn8:
				keyText = "8";
				setTextEnabled(keyText);
				break;
			case R.id.btn9:
				keyText = "9";
				setTextEnabled(keyText);
				break;
			// ( ) .
			case R.id.btnPeriod:
				keyText = ".";
				setTextEnabled(keyText);
				break;
			case R.id.btnLeftParenthesis:
				keyText = "(";
				setTextEnabled(keyText);
				break;
			case R.id.btnRightParenthesis:
				keyText = ")";
				setTextEnabled(keyText);
				break;
			// 사칙연산
			case R.id.btnPlus:
				keyText = "+";
				setTextEnabled(keyText);
				break;
			case R.id.btnMinus:
				keyText = "-";
				setTextEnabled(keyText);
				break;
			case R.id.btnAsterisk:
				keyText = "*";
				setTextEnabled(keyText);
				break;
			case R.id.btnDivide:
				keyText = "/";
				setTextEnabled(keyText);
				break;
			// bs, clear
			case R.id.btnBackSpace:
				setTextBackSpace();
				break;
			case R.id.btnClear:
				clearText();
				break;
			// =
			case R.id.btnEqualSign:
				forfundamentalRulesCalculate();
			default:
				break;
			}
		}
	};

	// 계산한다.
	public void forfundamentalRulesCalculate() {
		infixExpression = et1.getText().toString();

		// 중위 표 기식 -> 후위 표기식
		postfixExpression = c.getPostfix(infixExpression);
		nlog.puts("Infix : " + infixExpression);
		nlog.puts("Postfix : " + postfixExpression);

		if (c.validate(infixExpression)) {
			String fTitle = "계산식 오류";
			String fMsg = "입력한 계산식에 오류가 있습니다.\n .+-*/() 혹은 숫자만 입력 가능 합니다.";
			AlertDialog.Builder alert = new AlertDialog.Builder(this);
			alert.setTitle(fTitle);
			alert.setMessage(fMsg);
			alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					//clearText();
				}
			});
			alert.create();
			alert.show();
			return;
		}

		// 계산
		try {
			result = c.calculate(postfixExpression);
			nlog.puts("Calculation Result : " + result);
			String resultStr = Double.toString(result);
			et2.setText(resultStr);
		} catch (Exception e) {
			return;
		}
		return;
	}

	// 글자를 입력되게 한다.
	public void setTextEnabled(String keyText) {
		int curIndex = et1.getSelectionStart();
		String inputedStr = et1.getText().toString();
		String str = inputedStr.substring(0, curIndex) + keyText + inputedStr.substring(curIndex, inputedStr.length());
		et1.setText(str);
		Editable etext = et1.getText();
		Selection.setSelection(etext, curIndex + 1);
	}

	// 글자를 하나 지운다.
	public void setTextBackSpace() {
		int curIndex = et1.getSelectionStart();
		String inputedStr = et1.getText().toString();
		if (inputedStr.length() > 0) {
			try {
				String str = inputedStr.substring(0, curIndex - 1) + inputedStr.substring(curIndex, inputedStr.length());
				et1.setText(str);
				Editable etext = et1.getText();
				Selection.setSelection(etext, curIndex - 1);
			} catch (Exception e) {
			}
		}
	}

	// 커서를 설정한다.
	public void setCursor(String mode) {
		int curIndex = et1.getSelectionStart();
		Editable etext = et1.getText();
		try {
			if (mode.equals("first")) {
				Selection.setSelection(etext, 0);
			} else if (mode.equals("left")) {
				Selection.setSelection(etext, curIndex - 1);
			} else if (mode.equals("right")) {
				if (curIndex < etext.length()) {
					Selection.setSelection(etext, curIndex + 1);
				}
			} else if (mode.equals("last")) {
				Selection.setSelection(etext, etext.length());
			}
		} catch (Exception e) {
		}

	}

	// 글자를 전부 지운다.
	public void clearText() {
		et1.setText("");
		et2.setText("");
	}

	// 에디트텍스트를 포커스 되지 못하게 한다.
	public void disEnableInput() {
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(et1.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
		imm.hideSoftInputFromWindow(et2.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
		et1.setInputType(InputType.TYPE_NULL);
		et2.setInputType(InputType.TYPE_NULL);
	}

}
